<!DOCTYPE html>
<html>
<head>
    <title>文章新增</title>
    {% include 'system/common/header.html' %}</head>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/aieditor/style.css') }}"/>
    <style>

    </style>
<body>
<form class="layui-form" action="">
    <input type="hidden" name="type" id="article-type" value="rich">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">文章名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="标签名称"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">文章别名</label>
                    <div class="layui-input-block">
                        <input type="text" name="slug" lay-verify="required" autocomplete="off" placeholder="别名"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">分类目录</label>
                    <div class="layui-input-block">
                        <div class="layui-input-inline" style="width: 100%;">
                            <input type="text" id="category-display" placeholder="请选择分类" readonly class="layui-input" style="cursor: pointer;">
                            <input type="hidden" name="category_id" id="category-id" lay-verify="required">
                        </div>
                        <div id="category-tree" style="display: none; position: absolute; z-index: 1000; background: white; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); max-height: 300px; overflow-y: auto; width: 100%;">
                            <div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
                                <input type="text" id="category-search" placeholder="搜索分类..." class="layui-input" style="height: 32px; font-size: 12px;">
                            </div>
                            <div id="category-tree-content"></div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">标签</label>
                    <div class="layui-input-block">
                        <div id="tag-container" class="layui-form-mid">
                            <div class="layui-btn-group" id="selected-tags"></div>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="add-tag-btn">
                                <i class="layui-icon layui-icon-add-1"></i> 添加标签
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章摘要</label>
                    <div class="layui-input-block">
                        <textarea placeholder="文章摘要" name="excerpt" class="layui-textarea"></textarea>
                    </div>
                </div>
                
                <!-- 特色图像 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">特色图像</label>
                    <div class="layui-input-block">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <input type="text" name="featured_image" id="featured-image-url" placeholder="请输入图片地址或上传图片" class="layui-input">
                            </div>
                            <div class="layui-col-md6">
                                <button type="button" class="layui-btn layui-btn-primary" id="upload-featured-image">
                                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="paste-image-url">
                                    <i class="layui-icon layui-icon-link"></i> 粘贴地址
                                </button>
                            </div>
                        </div>
                        <div id="featured-image-preview" style="margin-top: 10px; display: none;">
                            <img id="preview-img" src="" alt="特色图像预览" style="max-width: 300px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 2px;">
                            <div style="margin-top: 5px;">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="remove-featured-image">
                                    <i class="layui-icon layui-icon-close"></i> 移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章内容</label>
                    <div class="layui-input-block">
                        <div id="editor" style="height: 550px"></div>
                    </div>
                </div>
                
                <!-- SEO信息 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_title" placeholder="SEO标题（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_keywords" placeholder="SEO关键词，多个关键词用逗号分隔（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">SEO描述</label>
                    <div class="layui-input-block">
                        <textarea name="meta_description" placeholder="SEO描述（可选）" class="layui-textarea" style="height: 80px;"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="post-save">
                <i class="layui-icon layui-icon-ok"></i>
                草稿
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="publish-btn">
                <i class="layui-icon layui-icon-release"></i>
                发布
            </button>
        </div>
    </div>
</form>
{% include 'system/common/footer.html' %}
<script src="{{ url_for('admin.static', filename='system/component/aieditor/index.js') }}"></script>
<script>
// 调试表单提交功能
console.log('=== 表单提交调试脚本 ===');

// 检查页面元素
console.log('检查页面元素...');
console.log('表单元素:', document.querySelector('form.layui-form'));
console.log('提交按钮:', document.querySelector('button[lay-filter="post-save"]'));

// 检查Layui是否加载
console.log('检查Layui...');
if (typeof layui !== 'undefined') {
    console.log('Layui已加载');
    console.log('Layui版本:', layui.v);
} else {
    console.error('Layui未加载');
}

// 检查jQuery是否加载
console.log('检查jQuery...');
if (typeof $ !== 'undefined') {
    console.log('jQuery已加载');
    console.log('jQuery版本:', $.fn.jquery);
} else {
    console.error('jQuery未加载');
}

// 手动绑定表单提交事件
console.log('手动绑定表单提交事件...');
document.addEventListener('DOMContentLoaded', function() {
    const submitBtn = document.querySelector('button[lay-filter="post-save"]');
    if (submitBtn) {
        console.log('找到提交按钮，添加点击事件监听器');
        submitBtn.addEventListener('click', function(e) {
            console.log('提交按钮被点击');
            e.preventDefault();
            
            // 获取表单数据
            const form = document.querySelector('form.layui-form');
            const formData = new FormData(form);
            const data = {};
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            console.log('表单数据:', data);
            
            // 获取编辑器内容
            let editorContent = '';
            
            // 首先尝试从DOM获取内容
            const editorElement = document.querySelector('#editor');
            if (editorElement) {
                const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                                      editorElement.querySelector('.ai-editor-content') ||
                                      editorElement.querySelector('.editor-content') ||
                                      editorElement;
                
                if (contentElement) {
                    editorContent = contentElement.innerHTML;
                    console.log('从DOM获取到编辑器内容:', editorContent);
                }
            }
            
            // 如果DOM内容为空，尝试使用AiEditor API
            if (!editorContent && window.aiEditor) {
                try {
                    if (typeof window.aiEditor.getContent === 'function') {
                        editorContent = window.aiEditor.getContent();
                    } else if (typeof window.aiEditor.getHtml === 'function') {
                        editorContent = window.aiEditor.getHtml();
                    } else if (typeof window.aiEditor.getMarkdown === 'function') {
                        editorContent = window.aiEditor.getMarkdown();
                    } else if (typeof window.aiEditor.getText === 'function') {
                        editorContent = window.aiEditor.getText();
                    }
                    console.log('从AiEditor API获取到内容:', editorContent);
                } catch (error) {
                    console.error('AiEditor API调用失败:', error);
                }
            }
            
            if (!editorContent) {
                console.warn('无法获取编辑器内容');
            }
            
            // 构建提交数据
            const submitData = {
                title: data.title,
                slug: data.slug,
                excerpt: data.excerpt,
                content: editorContent,
                category_id: data.category_id ? parseInt(data.category_id) : null,
                tag_ids: selectedTags.map(tag => tag.id),
                meta_title: data.meta_title || '',
                meta_keywords: data.meta_keywords || '',
                meta_description: data.meta_description || '',
                status: 'draft'
            };
            
            console.log('准备提交的数据:', submitData);
            
            // 发送AJAX请求
            if (typeof $ !== 'undefined') {
                $.ajax({
                    url: '/admin/cms/post/save',
                    data: JSON.stringify(submitData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'post',
                    success: function(result) {
                        console.log('请求成功:', result);
                        if (result.success) {
                            alert('保存成功: ' + result.msg);
                        } else {
                            alert('保存失败: ' + result.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('请求失败:', xhr, status, error);
                        alert('保存失败: ' + error);
                    }
                });
            } else {
                console.error('jQuery未加载，无法发送AJAX请求');
            }
        });
    } else {
        console.error('未找到提交按钮');
    }
});

console.log('调试脚本加载完成');

// 全局变量
let selectedTags = [];
let allTags = [];

// 加载分类数据
function loadCategories() {
    layui.use(['jquery', 'tree'], function() {
        let $ = layui.jquery;
        let tree = layui.tree;
        console.log('开始加载分类数据...');
        $.ajax({
            url: '/admin/cms/post/categories',
            type: 'GET',
            success: function(result) {
                console.log('分类API响应:', result);
                if (result.success) {
                    console.log('分类数据:', result.data);
                    
                    // 转换数据格式为树形组件需要的格式
                    function convertToTreeData(categories) {
                        return categories.map(function(category) {
                            return {
                                id: category.id,
                                title: category.title,
                                children: category.children && category.children.length > 0 ? convertToTreeData(category.children) : []
                            };
                        });
                    }
                    
                    const treeData = convertToTreeData(result.data);
                    console.log('树形数据:', treeData);
                    
                    // 渲染树形组件
                    tree.render({
                        elem: '#category-tree-content',
                        data: treeData,
                        showLine: true,
                        click: function(obj) {
                            console.log('选择分类:', obj.data);
                            $('#category-display').val(obj.data.title);
                            $('#category-id').val(obj.data.id);
                            $('#category-tree').hide();
                        }
                    });
                    
                    // 绑定点击事件
                    $('#category-display').click(function() {
                        $('#category-tree').toggle();
                        if ($('#category-tree').is(':visible')) {
                            $('#category-search').focus();
                        }
                    });
                    
                    // 点击其他地方隐藏树形组件
                    $(document).click(function(e) {
                        if (!$(e.target).closest('#category-display, #category-tree').length) {
                            $('#category-tree').hide();
                        }
                    });
                    
                    // 搜索功能
                    $('#category-search').on('input', function() {
                        const searchText = $(this).val().toLowerCase().trim();
                        console.log('搜索文本:', searchText);
                        
                        if (!searchText) {
                            // 如果搜索框为空，显示所有分类
                            tree.render({
                                elem: '#category-tree-content',
                                data: treeData,
                                showLine: true,
                                click: function(obj) {
                                    console.log('选择分类:', obj.data);
                                    $('#category-display').val(obj.data.title);
                                    $('#category-id').val(obj.data.id);
                                    $('#category-tree').hide();
                                }
                            });
                            return;
                        }
                        
                        // 搜索匹配的分类
                        function searchCategories(categories, searchText) {
                            let results = [];
                            
                            for (let category of categories) {
                                // 检查当前分类是否匹配
                                if (category.title.toLowerCase().includes(searchText)) {
                                    results.push({
                                        id: category.id,
                                        title: category.title,
                                        children: []
                                    });
                                }
                                
                                // 递归搜索子分类
                                if (category.children && category.children.length > 0) {
                                    const childResults = searchCategories(category.children, searchText);
                                    results = results.concat(childResults);
                                }
                            }
                            
                            return results;
                        }
                        
                        const searchResults = searchCategories(treeData, searchText);
                        console.log('搜索结果:', searchResults);
                        
                        // 渲染搜索结果
                        if (searchResults.length > 0) {
                            tree.render({
                                elem: '#category-tree-content',
                                data: searchResults,
                                showLine: true,
                                click: function(obj) {
                                    console.log('选择分类:', obj.data);
                                    $('#category-display').val(obj.data.title);
                                    $('#category-id').val(obj.data.id);
                                    $('#category-tree').hide();
                                }
                            });
                        } else {
                            // 没有搜索结果
                            $('#category-tree-content').html('<div style="padding: 20px; text-align: center; color: #999;">没有找到匹配的分类</div>');
                        }
                    });
                    
                    // 搜索框回车键处理
                    $('#category-search').on('keydown', function(e) {
                        if (e.keyCode === 13) { // Enter键
                            e.preventDefault();
                            const firstResult = $('#category-tree-content .layui-tree-txt').first();
                            if (firstResult.length > 0) {
                                firstResult.click();
                            }
                        }
                    });
                    
                    console.log('分类数据加载完成');
                } else {
                    console.error('分类API返回失败:', result.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error('加载分类失败:', xhr, status, error);
                layer.msg('加载分类失败', {icon: 2});
            }
        });
    });
}

// 加载标签数据
function loadTags() {
    layui.use(['jquery'], function() {
        let $ = layui.jquery;
        console.log('开始加载标签数据...');
        $.ajax({
            url: '/admin/cms/post/tags',
            type: 'GET',
            success: function(result) {
                console.log('标签API响应:', result);
                if (result.success) {
                    allTags = result.data;
                    console.log('标签数据:', allTags);
                    console.log('标签数量:', allTags.length);
                } else {
                    console.error('标签API返回失败:', result.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error('加载标签失败:', xhr, status, error);
                layer.msg('加载标签失败', {icon: 2});
            }
        });
    });
}

// 显示标签选择弹窗
function showTagSelector() {
    layui.use(['jquery', 'layer', 'form'], function() {
        let $ = layui.jquery;
        let layer = layui.layer;
        let form = layui.form;
        
        let tagHtml = '<div style="padding: 20px;">';
        tagHtml += '<div class="layui-form-item">';
        tagHtml += '<label class="layui-form-label">搜索标签</label>';
        tagHtml += '<div class="layui-input-block">';
        tagHtml += '<input type="text" id="tag-search" placeholder="输入标签名称搜索" class="layui-input">';
        tagHtml += '</div>';
        tagHtml += '</div>';
        tagHtml += '<div id="tag-list" style="max-height: 300px; overflow-y: auto;">';
        
        allTags.forEach(function(tag) {
            const isSelected = selectedTags.some(t => t.id === tag.id);
            tagHtml += `<div class="layui-form-item">`;
            tagHtml += `<input type="checkbox" name="tag_${tag.id}" value="${tag.id}" title="${tag.title || tag.name || '未命名标签'}" ${isSelected ? 'checked' : ''}>`;
            tagHtml += `<label style="margin-left: 10px;">${tag.title || tag.name || '未命名标签'}</label>`;
            tagHtml += `</div>`;
        });
        
        tagHtml += '</div></div>';
        
        layer.open({
            type: 1,
            title: '选择标签',
            content: tagHtml,
            area: ['500px', '400px'],
            btn: ['确定', '取消'],
            yes: function(index) {
                // 获取选中的标签
                const checkedTags = [];
                allTags.forEach(function(tag) {
                    if ($(`input[name="tag_${tag.id}"]`).is(':checked')) {
                        checkedTags.push(tag);
                    }
                });
                
                selectedTags = checkedTags;
                renderSelectedTags();
                layer.close(index);
            }
        });
        
        // 绑定搜索功能
        $('#tag-search').on('input', function() {
            const searchText = $(this).val().toLowerCase();
            allTags.forEach(function(tag) {
                const checkbox = $(`input[name="tag_${tag.id}"]`);
                const item = checkbox.closest('.layui-form-item');
                if (tag.title.toLowerCase().includes(searchText)) {
                    item.show();
                } else {
                    item.hide();
                }
            });
        });
        
        form.render('checkbox');
    });
}

// 渲染已选择的标签
function renderSelectedTags() {
    layui.use(['jquery'], function() {
        let $ = layui.jquery;
        const container = $('#selected-tags');
        container.empty();
        
        console.log('渲染标签，当前标签数据:', selectedTags);
        console.log('标签数量:', selectedTags ? selectedTags.length : 0);
        
        if (selectedTags && selectedTags.length > 0) {
            selectedTags.forEach(function(tag) {
                const tagTitle = tag.title || tag.name || '未命名标签';
                console.log(`渲染标签: ${tagTitle} (ID: ${tag.id})`);
                container.append(`
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" data-tag-id="${tag.id}">
                        ${tagTitle}
                        <i class="layui-icon layui-icon-close" onclick="removeTag(${tag.id})"></i>
                    </button>
                `);
            });
        } else {
            console.log('没有标签数据，显示空状态');
            container.append('<span class="layui-text layui-text-color">暂无标签</span>');
        }
    });
}

// 移除标签
function removeTag(tagId) {
    selectedTags = selectedTags.filter(tag => tag.id !== tagId);
    renderSelectedTags();
}

// 绑定事件
layui.use(['form', 'jquery'], function() {
    let $ = layui.jquery;
    
    // 加载数据
    loadCategories();
    loadTags();
    
    // 绑定添加标签按钮
    $('#add-tag-btn').click(function() {
        showTagSelector();
    });

    // 特色图像功能
    // 上传图片
    $('#upload-featured-image').click(function() {
        // 创建一个隐藏的文件输入框
        let fileInput = $('<input type="file" accept="image/*" style="display: none;">');
        $('body').append(fileInput);
        
        fileInput.click();
        
        fileInput.on('change', function() {
            let file = this.files[0];
            if (file) {
                // 创建FormData对象
                let formData = new FormData();
                formData.append('image', file);
                formData.append('type', 'images');
                
                // 上传文件
                $.ajax({
                    url: '/admin/cms/post/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.errorCode === 0) {
                            let imageUrl = result.data.src;
                            $('#featured-image-url').val(imageUrl);
                            showImagePreview(imageUrl);
                            layer.msg('图片上传成功', {icon: 1});
                        } else {
                            layer.msg(result.msg || '上传失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('上传失败', {icon: 2});
                    }
                });
            }
            
            // 移除临时文件输入框
            fileInput.remove();
        });
    });
    
    // 粘贴图片地址
    $('#paste-image-url').click(function() {
        layer.prompt({
            title: '请输入图片地址',
            formType: 0,
            value: '',
            area: ['400px', '150px']
        }, function(value, index) {
            if (value && value.trim()) {
                $('#featured-image-url').val(value.trim());
                showImagePreview(value.trim());
                layer.close(index);
                layer.msg('图片地址已设置', {icon: 1});
            } else {
                layer.msg('请输入有效的图片地址', {icon: 2});
            }
        });
    });
    
    // 移除特色图像
    $('#remove-featured-image').click(function() {
        $('#featured-image-url').val('');
        $('#featured-image-preview').hide();
        layer.msg('特色图像已移除', {icon: 1});
    });
    
    // 显示图片预览
    function showImagePreview(imageUrl) {
        if (imageUrl && imageUrl.trim()) {
            $('#preview-img').attr('src', imageUrl);
            $('#featured-image-preview').show();
        } else {
            $('#featured-image-preview').hide();
        }
    }
    
    // 监听图片地址输入框变化
    $('#featured-image-url').on('input', function() {
        let imageUrl = $(this).val().trim();
        showImagePreview(imageUrl);
    });
    
    // 初始化特色图像预览（如果有值）
    let initialImageUrl = $('#featured-image-url').val();
    if (initialImageUrl) {
        showImagePreview(initialImageUrl);
    }
});

// 测试AiEditor API
function testAiEditorAPI() {
    console.log('=== 测试AiEditor API ===');
    console.log('window.aiEditor:', window.aiEditor);
    
    if (window.aiEditor) {
        console.log('AiEditor已初始化');
        const methods = Object.getOwnPropertyNames(window.aiEditor);
        console.log('AiEditor方法列表:', methods);
        
        // 测试常见方法
        ['getContent', 'getHtml', 'getMarkdown', 'getText', 'getValue'].forEach(method => {
            if (typeof window.aiEditor[method] === 'function') {
                console.log(`✓ ${method} 方法存在`);
            } else {
                console.log(`✗ ${method} 方法不存在`);
            }
        });
    } else {
        console.log('AiEditor未初始化');
    }
}

// 延迟测试AiEditor API
setTimeout(testAiEditorAPI, 3000);
</script>
    <script type="module">
        import {AiEditor} from "{{ url_for('admin.static', filename='system/component/aieditor/index.js') }}";
        
        // 等待DOM加载完成后初始化AiEditor
        document.addEventListener('DOMContentLoaded', function() {
            window.aiEditor = new AiEditor({
                element: "#editor",
                placeholder: "点击输入内容...",
                content: '',
            image: {
                allowBase64: false,
                defaultSize: 350,
                uploadUrl: "/admin/cms/post/upload",
                uploadFormName: "image", //上传时的文件表单名称
                uploaderEvent: {
                    onUploadBefore: (file, uploadUrl, headers) => {
                        //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        console.log('图片上传开始:', file.name);
                    },
                    onSuccess: (file, response) => {
                        //监听图片上传成功
                        console.log('图片上传成功:', response);
                        //注意：
                        // 1、如果此方法返回 false，则图片不会被插入到编辑器
                        // 2、可以在这里返回一个新的 json 给编辑器
                    },
                    onFailed: (file, response) => {
                        //监听图片上传失败，或者返回的 json 信息不正确
                        console.error('图片上传失败:', response);
                    },
                    onError: (file, error) => {
                        //监听图片上传错误，比如网络超时等
                        console.error('图片上传错误:', error);
                    },
                },
                bubbleMenuItems: ["AlignLeft", "AlignCenter", "AlignRight", "delete"]
            },
            video: {
                uploadUrl: "/admin/cms/post/upload",
                uploadFormName: "video", //上传时的文件表单名称
                uploaderEvent: {
                    onUploadBefore: (file, uploadUrl, headers) => {
                        //监听视频上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        console.log('视频上传开始:', file.name);
                    },
                    onSuccess: (file, response) => {
                        //监听视频上传成功
                        console.log('视频上传成功:', response);
                        //注意：
                        // 1、如果此方法返回 false，则视频不会被插入到编辑器
                        // 2、可以在这里返回一个新的 json 给编辑器
                    },
                    onFailed: (file, response) => {
                        //监听视频上传失败，或者返回的 json 信息不正确
                        console.error('视频上传失败:', response);
                    },
                    onError: (file, error) => {
                        //监听视频上传错误，比如网络超时等
                        console.error('视频上传错误:', error);
                    },
                }
            },
            attachment: {
                uploadUrl: "/admin/cms/post/upload",
                uploadFormName: "attachment", //上传时的文件表单名称
                uploaderEvent: {
                    onUploadBefore: (file, uploadUrl, headers) => {
                        //监听附件上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        console.log('附件上传开始:', file.name);
                    },
                    onSuccess: (file, response) => {
                        //监听附件上传成功
                        console.log('附件上传成功:', response);
                        //注意：
                        // 1、如果此方法返回 false，则附件不会被插入到编辑器
                        // 2、可以在这里返回一个新的 json 给编辑器
                    },
                    onFailed: (file, response) => {
                        //监听附件上传失败，或者返回的 json 信息不正确
                        console.error('附件上传失败:', response);
                    },
                    onError: (file, error) => {
                        //监听附件上传错误，比如网络超时等
                        console.error('附件上传错误:', error);
                    },
                }
            },
            ai: {
                models: {
                    spark: {
                        appId: "***",
                        apiKey: "***",
                        apiSecret: "***",
                    }
                }
            },
        });
        });
    </script>
<script>
  layui.use(['form', 'jquery'], function () {
    let form = layui.form
    let $ = layui.jquery
    
    console.log('Layui form 初始化完成');
    console.log('Form对象:', form);
    console.log('jQuery对象:', $);

    // 获取URL参数并设置文章类型
    function getUrlParameter(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
      var results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }
    
    // 设置文章类型
    var articleType = getUrlParameter('type') || 'rich';
    $('#article-type').val(articleType);
    console.log('文章类型:', articleType);

    // 测试表单事件绑定
    console.log('绑定表单提交事件...');
    // 草稿按钮事件处理
    form.on('submit(post-save)', function (data) {
      console.log('草稿按钮事件触发', data);
      
      // 获取AiEditor的内容
      let editorContent = '';
      
      // 首先尝试从DOM获取内容（最可靠的方法）
      const editorElement = document.querySelector('#editor');
      if (editorElement) {
        // 查找编辑器内的内容区域
        const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                              editorElement.querySelector('.ai-editor-content') ||
                              editorElement.querySelector('.editor-content') ||
                              editorElement;
        
        if (contentElement) {
          editorContent = contentElement.innerHTML;
          console.log('从DOM获取到编辑器内容:', editorContent);
        }
      }
      
      // 如果DOM内容为空，尝试使用AiEditor API
      if (!editorContent && window.aiEditor) {
        try {
          if (typeof window.aiEditor.getContent === 'function') {
            editorContent = window.aiEditor.getContent();
          } else if (typeof window.aiEditor.getHtml === 'function') {
            editorContent = window.aiEditor.getHtml();
          } else if (typeof window.aiEditor.getMarkdown === 'function') {
            editorContent = window.aiEditor.getMarkdown();
          } else if (typeof window.aiEditor.getText === 'function') {
            editorContent = window.aiEditor.getText();
          }
          console.log('从AiEditor API获取到内容:', editorContent);
        } catch (error) {
          console.error('AiEditor API调用失败:', error);
        }
      }
      
      if (!editorContent) {
        console.warn('无法获取编辑器内容');
      }
      
      // 构建提交数据
      let submitData = {
        title: data.field.title,
        slug: data.field.slug,
        excerpt: data.field.excerpt,
        featured_image: data.field.featured_image || '',
        content: editorContent,
        category_id: data.field.category_id ? parseInt(data.field.category_id) : null,
        tag_ids: selectedTags.map(tag => tag.id),
        meta_title: data.field.meta_title || '',
        meta_keywords: data.field.meta_keywords || '',
        meta_description: data.field.meta_description || '',
        type: data.field.type || 'rich',  // 文章类型
        status: 'draft'  // 保存为草稿
      }
      
      console.log('准备提交的数据:', submitData);
      console.log('提交URL:', '/admin/cms/post/save');
      
      $.ajax({
        url: '/admin/cms/post/save',
        data: JSON.stringify(submitData),
        dataType: 'json',
        contentType: 'application/json',
        type: 'post',
        success: function (result) {
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
              parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
              parent.layui.table.reload('post-table')  // 修正表格名称
            })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
          }
        },
        error: function (xhr, status, error) {
          layer.msg('保存失败: ' + error, { icon: 2, time: 2000 })
        }
      })
      return false
    })
    
    // 发布按钮事件处理
    $('#publish-btn').click(function() {
      console.log('发布按钮事件触发');
      
      // 获取表单数据 - 使用与草稿按钮相同的方式
      let formData = {};
      $('form.layui-form input, form.layui-form textarea, form.layui-form select').each(function() {
        let name = $(this).attr('name');
        let value = $(this).val();
        if (name) {
          formData[name] = value;
        }
      });
      
      console.log('获取到的表单数据:', formData);
      
      // 获取AiEditor的内容
      let editorContent = '';
      
      // 首先尝试从DOM获取内容（最可靠的方法）
      const editorElement = document.querySelector('#editor');
      if (editorElement) {
        // 查找编辑器内的内容区域
        const contentElement = editorElement.querySelector('[contenteditable="true"]') || 
                              editorElement.querySelector('.ai-editor-content') ||
                              editorElement.querySelector('.editor-content') ||
                              editorElement;
        
        if (contentElement) {
          editorContent = contentElement.innerHTML;
          console.log('从DOM获取到编辑器内容:', editorContent);
        }
      }
      
      // 如果DOM内容为空，尝试使用AiEditor API
      if (!editorContent && window.aiEditor) {
        try {
          if (typeof window.aiEditor.getContent === 'function') {
            editorContent = window.aiEditor.getContent();
          } else if (typeof window.aiEditor.getHtml === 'function') {
            editorContent = window.aiEditor.getHtml();
          } else if (typeof window.aiEditor.getMarkdown === 'function') {
            editorContent = window.aiEditor.getMarkdown();
          } else if (typeof window.aiEditor.getText === 'function') {
            editorContent = window.aiEditor.getText();
          }
          console.log('从AiEditor API获取到内容:', editorContent);
        } catch (error) {
          console.error('AiEditor API调用失败:', error);
        }
      }
      
      if (!editorContent) {
        console.warn('无法获取编辑器内容');
      }
      
              // 构建提交数据
        let submitData = {
            title: formData.title,
            slug: formData.slug,
            excerpt: formData.excerpt,
            featured_image: formData.featured_image || '',
            content: editorContent,
            category_id: formData.category_id ? parseInt(formData.category_id) : null,
            tag_ids: selectedTags.map(tag => tag.id),
            meta_title: formData.meta_title || '',
            meta_keywords: formData.meta_keywords || '',
            meta_description: formData.meta_description || '',
            type: formData.type || 'rich',  // 文章类型
            status: 'published'  // 发布状态
        }
      
      console.log('准备发布的数据:', submitData);
      console.log('发布URL:', '/admin/cms/post/save');
      
      $.ajax({
        url: '/admin/cms/post/save',
        data: JSON.stringify(submitData),
        dataType: 'json',
        contentType: 'application/json',
        type: 'post',
        success: function (result) {
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
              parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
              parent.layui.table.reload('post-table')  // 修正表格名称
            })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
          }
        },
        error: function (xhr, status, error) {
          layer.msg('发布失败: ' + error, { icon: 2, time: 2000 })
        }
      })
    })
  })
</script>

</body>
</html>